package com.teradata.feedProc;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.NoSuchElementException;

import com.teradata.feedProc.beans.FeedInfo;
import com.teradata.feedProc.beans.FieldInfo;

/**
 * Implementation of IFileIterator.
 */
public class FileIterator implements IFileIterator<IFileLine> {

	private InputStreamReader in = null;
	private int char_in;
	private String string = null;
	private final FeedInfo feedInfo;
	private final List<FieldInfo> fieldInfoList;

	public FileIterator(final FeedInfo feedInfo, final List<FieldInfo> fieldInfoList) throws IOException {
		final String finalFile = feedInfo.getStrSrcObjName();
		final File file = new File(finalFile);

		// Check file exists
		if (!file.exists()) {
			System.err.println("Unable to find source file. Please try again.");
			System.exit(1);
		}

		this.feedInfo = feedInfo;
		this.fieldInfoList = fieldInfoList;
		try {
			// Streams in records one character at a time as to translate
			// non-printable characters correctly.
			in = new InputStreamReader(new BufferedInputStream(new FileInputStream(file), 8192 * 1024), "ISO-8859-1");

			char_in = in.read();
			while (char_in != -1 && (char) char_in != '\n') {
				string += (char) char_in;
				char_in = in.read();
			}

			if (string == null) {
				in.close();
				in = null;
			}
		} catch (IOException ioe) {
			string = null;
			if (in != null) {
				try {
					in.close();
				} catch (IOException ioe2) {
				}
			}
			in = null;
			throw ioe;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean hasMoreLines() {
		return string != null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public FileLine getNextLine() throws NoSuchElementException {

		// return the string from the 5th element to drop the "NULL" that starts
		// the line
		String returnString = string.substring(4);

		try {
			if (string == null) {
				throw new NoSuchElementException("Next line is not available");
			} else {
				string = null;
				char_in = in.read();
				while (char_in != -1 && (char) char_in != '\n') {
					string += (char) char_in;
					char_in = in.read();
				}

				if (string == null && in != null) {
					in.close();
					in = null;
				}
			}
		} catch (Exception ex) {
			throw new NoSuchElementException("Exception caught in FileIterator.nextLine() " + ex);
		}

		return new FileLine(returnString, feedInfo, fieldInfoList);
	}

	@Override
	protected void finalize() throws Throwable {
		try {
			string = null;
			if (in != null) {
				try {
					in.close();
				} catch (Exception ex) {
				}
			}
			in = null;
		} finally {
			super.finalize();
		}
	}
}
